<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import {
  ElCard,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElTag,
  ElDatePicker,
  ElRow,
  ElCol,
  ElLoading,
  ElEmpty,
  ElMessage
} from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import request from '@/utils/request'

interface User {
  id: string
  loginId: string
  email: string
  nickname?: string
  name?: string
  role: string
  status: string
  createdAt: string
  wallet?: {
    pointsBalance: string
  }
}

interface UserLog {
  id: string
  type: 'recharge' | 'withdrawal' | 'gift' | 'chat_gift'
  userId: string
  user: {
    id: string
    loginId: string
    nickname?: string
    name?: string
  }
  amount?: number
  points?: string
  status?: string
  method?: string
  referenceNo?: string
  quantity?: number
  gift?: {
    id: string
    name: string
    iconUrl?: string
  }
  channel?: {
    id: string
    name: string
  }
  room?: {
    id: string
    title?: string
  }
  receiver?: {
    id: string
    loginId: string
    nickname?: string
    name?: string
  }
  createdAt: string
  description: string
}

interface LogsResponse {
  logs: UserLog[]
  total: number
  page: number
  limit: number
  user?: User
}

const loading = ref(false)
const searchLoading = ref(false)
const logs = ref<UserLog[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const selectedUser = ref<User | null>(null)

// 搜索条件
const searchForm = ref({
  search: '',
  type: 'all',
  startDate: '',
  endDate: ''
})

// 로그 유형 옵션
const logTypeOptions = [
  { label: '전체', value: 'all' },
  { label: '충전', value: 'recharge' },
  { label: '출금', value: 'withdrawal' },
  { label: '라이브 선물', value: 'gift' },
  { label: '채팅 선물', value: 'chat_gift' }
]

// 사용자 로그 가져오기
const fetchUserLogs = async () => {
  try {
    loading.value = true
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value,
      type: searchForm.value.type
    }

    if (searchForm.value.search.trim()) {
      params.search = searchForm.value.search.trim()
    }

    if (searchForm.value.startDate) {
      params.startDate = searchForm.value.startDate
    }

    if (searchForm.value.endDate) {
      params.endDate = searchForm.value.endDate
    }

    const response = await request.get('/api/admin/user-logs', { params })
    const data: LogsResponse = response.data

    logs.value = data.logs
    total.value = data.total
    selectedUser.value = data.user || null
  } catch (error) {
    console.error('사용자 로그 가져오기 실패:', error)
    ElMessage.error('사용자 로그 가져오기 실패')
  } finally {
    loading.value = false
  }
}

// 사용자 로그 검색
const handleSearch = () => {
  currentPage.value = 1
  fetchUserLogs()
}

// 검색 초기화
const handleReset = () => {
  searchForm.value = {
    search: '',
    type: 'all',
    startDate: '',
    endDate: ''
  }
  selectedUser.value = null
  currentPage.value = 1
  fetchUserLogs()
}

// 페이지 변경
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchUserLogs()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchUserLogs()
}

// 로그 유형 포맷
const formatLogType = (type: string) => {
  const typeMap: Record<string, { label: string; type: 'primary' | 'success' | 'warning' | 'info' | 'danger' }> = {
    recharge: { label: '충전', type: 'success' },
    withdrawal: { label: '출금', type: 'warning' },
    gift: { label: '라이브 선물', type: 'primary' },
    chat_gift: { label: '채팅 선물', type: 'info' }
  }
  return typeMap[type] || { label: type, type: 'info' as const }
}

// 상태 포맷
const formatStatus = (status: string) => {
  const statusMap: Record<string, { label: string; type: 'primary' | 'success' | 'warning' | 'info' | 'danger' }> = {
    pending: { label: '심사 대기', type: 'warning' },
    approved: { label: '승인됨', type: 'success' },
    rejected: { label: '거부됨', type: 'danger' }
  }
  return statusMap[status] || { label: status, type: 'info' as const }
}

// 사용자 표시명 포맷
const formatUserName = (user: any) => {
  return user.nickname || user.name || user.loginId
}

// 숫자 포맷
const formatNumber = (num: string | number) => {
  const n = typeof num === 'string' ? parseInt(num) : num
  return n.toLocaleString()
}

// 금액 포맷
const formatAmount = (amount: number) => {
  return '¥' + amount.toLocaleString()
}

// 시간 포맷
const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

onMounted(() => {
  fetchUserLogs()
})
</script>

<template>
  <div class="user-logs-container">
    <div class="page-header">
      <h1 class="page-title">사용자 로그</h1>
      <p class="page-subtitle">사용자 활동 기록 보기, 충전, 출금, 선물 발송 등 포함</p>
    </div>

    <!-- 검색 영역 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.search"
            placeholder="사용자 검색 (사용자명/이메일/닉네임)"
            :prefix-icon="Search"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.type" placeholder="로그 유형">
            <el-option
              v-for="option in logTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-date-picker
            v-model="searchForm.startDate"
            type="date"
            placeholder="시작 날짜"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="5">
          <el-date-picker
            v-model="searchForm.endDate"
            type="date"
            placeholder="종료 날짜"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch" :loading="searchLoading">
            검색
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            초기화
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 사용자 정보 카드 -->
    <el-card v-if="selectedUser" class="user-info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>사용자 정보</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="info-item">
            <span class="label">사용자 ID:</span>
            <span class="value">{{ selectedUser.loginId }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="label">이메일:</span>
            <span class="value">{{ selectedUser.email }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="label">닉네임:</span>
            <span class="value">{{ selectedUser.nickname || selectedUser.name || '-' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="label">포인트 잔액:</span>
            <span class="value">{{ formatNumber(selectedUser.wallet?.pointsBalance || '0') }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 로그 목록 -->
    <el-card class="logs-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>활동 로그</span>
          <span class="total-count">총 {{ total }}개 기록</span>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="logs"
        stripe
        style="width: 100%"
        empty-text="로그 기록이 없습니다"
      >
        <el-table-column prop="type" label="유형" width="100">
          <template #default="{ row }">
            <el-tag :type="formatLogType(row.type).type" size="small">
              {{ formatLogType(row.type).label }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="user" label="사용자" width="150">
          <template #default="{ row }">
            <div>
              <div class="user-name">{{ formatUserName(row.user) }}</div>
              <div class="user-id">{{ row.user.loginId }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="설명" min-width="300">
          <template #default="{ row }">
            <div class="log-description">{{ row.description }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="amount" label="금액/포인트" width="120">
          <template #default="{ row }">
            <div v-if="row.amount" class="amount">{{ formatAmount(row.amount) }}</div>
            <div v-if="row.points" class="points">{{ formatNumber(row.points) }} 포인트</div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="상태" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status" :type="formatStatus(row.status).type" size="small">
              {{ formatStatus(row.status).label }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="시간" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.user-logs-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.user-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-count {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-item .label {
  font-weight: 500;
  color: var(--el-text-color-regular);
  margin-right: 8px;
  min-width: 80px;
}

.info-item .value {
  color: var(--el-text-color-primary);
}

.logs-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.logs-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.user-id {
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.log-description {
  line-height: 1.5;
}

.amount {
  color: var(--el-color-success);
  font-weight: 500;
}

.points {
  color: var(--el-color-primary);
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
